from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from app import db
from app.models import SystemConfig, OperationLog
from app.utils.response import success_response, error_response, paginated_response
from app.utils.decorators import admin_required
from loguru import logger

system_bp = Blueprint('system', __name__)

@system_bp.route('/configs', methods=['GET'])
@admin_required
def get_configs():
    """获取系统配置列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = min(request.args.get('per_page', 20, type=int), 100)
        search = request.args.get('search', '')
        
        query = SystemConfig.query
        
        if search:
            query = query.filter(
                db.or_(
                    SystemConfig.config_key.contains(search),
                    SystemConfig.description.contains(search)
                )
            )
        
        pagination = query.order_by(SystemConfig.config_key.asc()).paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )
        
        return paginated_response(
            [config.to_dict() for config in pagination.items],
            page,
            per_page,
            pagination.total
        )
        
    except Exception as e:
        logger.error(f"获取系统配置失败: {e}")
        return error_response('获取系统配置失败', 500)

@system_bp.route('/configs/<key>', methods=['GET'])
def get_config(key):
    """获取单个配置值"""
    try:
        config = SystemConfig.query.filter_by(config_key=key).first()
        if not config:
            return error_response('配置不存在', 404)
        
        return success_response(config.to_dict())
        
    except Exception as e:
        logger.error(f"获取配置失败: {e}")
        return error_response('获取配置失败', 500)

@system_bp.route('/configs', methods=['POST'])
@admin_required
def create_config():
    """创建系统配置"""
    try:
        data = request.get_json()
        config_key = data.get('config_key')
        config_value = data.get('config_value')
        description = data.get('description', '')
        
        if not config_key or config_value is None:
            return error_response('配置键和值不能为空', 400)
        
        # 检查配置键是否已存在
        existing = SystemConfig.query.filter_by(config_key=config_key).first()
        if existing:
            return error_response('配置键已存在', 400)
        
        config = SystemConfig(
            config_key=config_key,
            config_value=config_value,
            description=description
        )
        
        db.session.add(config)
        db.session.commit()
        
        # 记录操作日志
        current_admin_id = get_jwt_identity().split('_')[1]
        OperationLog.log_operation(
            action='create_config',
            description=f'创建系统配置: {config_key}',
            admin_id=current_admin_id,
            resource_type='system_config',
            resource_id=config.id
        )
        
        return success_response(config.to_dict(), '配置创建成功')
        
    except Exception as e:
        logger.error(f"创建系统配置失败: {e}")
        return error_response('创建系统配置失败', 500)

@system_bp.route('/configs/<key>', methods=['PUT'])
@admin_required
def update_config(key):
    """更新系统配置"""
    try:
        config = SystemConfig.query.filter_by(config_key=key).first()
        if not config:
            return error_response('配置不存在', 404)
        
        data = request.get_json()
        config_value = data.get('config_value')
        description = data.get('description')
        
        if config_value is not None:
            config.config_value = config_value
        if description is not None:
            config.description = description
        
        db.session.commit()
        
        # 记录操作日志
        current_admin_id = get_jwt_identity().split('_')[1]
        OperationLog.log_operation(
            action='update_config',
            description=f'更新系统配置: {key}',
            admin_id=current_admin_id,
            resource_type='system_config',
            resource_id=config.id
        )
        
        return success_response(config.to_dict(), '配置更新成功')
        
    except Exception as e:
        logger.error(f"更新系统配置失败: {e}")
        return error_response('更新系统配置失败', 500)

@system_bp.route('/configs/<key>', methods=['DELETE'])
@admin_required
def delete_config(key):
    """删除系统配置"""
    try:
        config = SystemConfig.query.filter_by(config_key=key).first()
        if not config:
            return error_response('配置不存在', 404)
        
        config_id = config.id
        db.session.delete(config)
        db.session.commit()
        
        # 记录操作日志
        current_admin_id = get_jwt_identity().split('_')[1]
        OperationLog.log_operation(
            action='delete_config',
            description=f'删除系统配置: {key}',
            admin_id=current_admin_id,
            resource_type='system_config',
            resource_id=config_id
        )
        
        return success_response(None, '配置删除成功')
        
    except Exception as e:
        logger.error(f"删除系统配置失败: {e}")
        return error_response('删除系统配置失败', 500)

@system_bp.route('/logs', methods=['GET'])
@admin_required
def get_logs():
    """获取操作日志"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = min(request.args.get('per_page', 20, type=int), 100)
        action = request.args.get('action', '')
        resource_type = request.args.get('resource_type', '')
        admin_id = request.args.get('admin_id', type=int)
        
        query = OperationLog.query
        
        if action:
            query = query.filter(OperationLog.action.contains(action))
        if resource_type:
            query = query.filter_by(resource_type=resource_type)
        if admin_id:
            query = query.filter_by(admin_id=admin_id)
        
        pagination = query.order_by(OperationLog.created_at.desc()).paginate(
            page=page,
            per_page=per_page,
            error_out=False
        )
        
        logs = []
        for log in pagination.items:
            log_dict = log.to_dict()
            # 添加管理员信息
            if log.admin_id:
                from app.models import Admin
                admin = Admin.query.get(log.admin_id)
                log_dict['admin'] = admin.to_dict() if admin else None
            logs.append(log_dict)
        
        return paginated_response(
            logs,
            page,
            per_page,
            pagination.total
        )
        
    except Exception as e:
        logger.error(f"获取操作日志失败: {e}")
        return error_response('获取操作日志失败', 500)

@system_bp.route('/stats', methods=['GET'])
@admin_required
def get_system_stats():
    """获取系统统计信息"""
    try:
        from app.models import User, Article, Question, Exam, Certificate, ExamRecord
        
        # 基础统计
        stats = {
            'total_users': User.query.count(),
            'total_articles': Article.query.count(),
            'total_questions': Question.query.count(),
            'total_exams': Exam.query.count(),
            'total_certificates': Certificate.query.count(),
            'total_exam_records': ExamRecord.query.count(),
        }
        
        # 今日统计
        from datetime import datetime, timedelta
        today = datetime.utcnow().date()
        
        today_stats = {
            'new_users': User.query.filter(
                db.func.date(User.created_at) == today
            ).count(),
            'new_articles': Article.query.filter(
                db.func.date(Article.created_at) == today
            ).count(),
            'new_exam_records': ExamRecord.query.filter(
                db.func.date(ExamRecord.created_at) == today
            ).count(),
            'new_certificates': Certificate.query.filter(
                db.func.date(Certificate.created_at) == today
            ).count(),
        }
        
        # 活跃用户统计（最近7天）
        seven_days_ago = datetime.utcnow() - timedelta(days=7)
        active_users = User.query.filter(User.last_login_at >= seven_days_ago).count()
        
        # 考试通过率
        total_exams = ExamRecord.query.count()
        passed_exams = ExamRecord.query.filter_by(is_passed=True).count()
        pass_rate = (passed_exams / total_exams * 100) if total_exams > 0 else 0
        
        stats.update({
            'today_stats': today_stats,
            'active_users': active_users,
            'pass_rate': round(pass_rate, 2)
        })
        
        return success_response(stats)
        
    except Exception as e:
        logger.error(f"获取系统统计失败: {e}")
        return error_response('获取系统统计失败', 500)

@system_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查"""
    try:
        # 检查数据库连接
        db.session.execute('SELECT 1')
        
        return success_response({
            'status': 'healthy',
            'timestamp': datetime.utcnow().isoformat(),
            'message': '好爸爸100问服务运行正常'
        })
        
    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        return error_response('服务异常', 500) 